//
//  SWNavigationController.swift
//  SkylowAPP
//
//  Created by 青色石头 on 2024/9/21.
//


import UIKit

public class SWNavigationController: UINavigationController {
    
    /// 导航栏默认的 背景图
    public static var defaultNavBackgroundImage: UIImage? = .navBackgroundImage
    
    /// 导航栏默认的 返回图
    public static var defaultNavBarBackImage: UIImage? = UIImage(named: "ic_nav_back")
    
    static let navDefaultConfig: Void = {
        let appearance = UINavigationBarAppearance()
        appearance.backgroundImage = .navBackgroundImage
        appearance.titleTextAttributes = [.foregroundColor: UIColor.white,
                                          .font: UIFont.medium(16)]
        appearance.shadowImage = UIImage()
        
        let navBar = UINavigationBar.appearance()
        navBar.tintColor = .white
        
        navBar.standardAppearance = appearance
        navBar.compactAppearance = appearance
        navBar.scrollEdgeAppearance = appearance
        
        
        
        let barItem = UIBarButtonItem.appearance()
        barItem.setTitleTextAttributes([.foregroundColor: UIColor.white, .font: UIFont.medium(16)], for: .normal)
        barItem.setTitleTextAttributes([.foregroundColor: UIColor.white, .font: UIFont.medium(16)], for: .highlighted)
        barItem.setTitleTextAttributes([.foregroundColor: UIColor.white.withAlphaComponent(0.4), .font: UIFont.medium(16)], for: .disabled)
    }()
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        if responds(to: #selector(getter: interactivePopGestureRecognizer)) {
            interactivePopGestureRecognizer?.delegate = self
            interactivePopGestureRecognizer?.isEnabled = true
        }
        delegate = self
        
        type(of: self).navDefaultConfig
    }
    
    public override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if viewControllers.count > 0 {
            viewController.hidesBottomBarWhenPushed = true
            Pai_configNavigationBarBackItem(viewController)
        }
        super.pushViewController(viewController, animated: animated)
    }
    
    public override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) {
        if viewControllers.count > 0 {
            for (index, vc) in viewControllers.enumerated() {
                if index == 0 {
                    vc.hidesBottomBarWhenPushed = false;
                }else {
                    vc.hidesBottomBarWhenPushed = true;
                    Pai_configNavigationBarBackItem(vc)
                }
            }
        }
        super.setViewControllers(viewControllers, animated: animated)
    }
    
    /// 配置控制器的返回键
    ///
    /// - Parameter viewController: 等待配置的控制器
    private func Pai_configNavigationBarBackItem(_ viewController: UIViewController) {
        var backBarItem: UIBarButtonItem?
        if let vc = viewController as? SWViewControllerNavigationConfigProtocol {
            var backImg: UIImage?
            if let navBackImageF = vc.navBackImage, let vc_backImg = navBackImageF() {
                backImg = vc_backImg
            }else {
                backImg = type(of: self).defaultNavBarBackImage
            }
            
            if vc.responds(to: #selector(SWViewControllerNavigationConfigProtocol.navBackAction)) {
                backBarItem = UIBarButtonItem(image: backImg, style: .plain, target: viewController, action: #selector(SWViewControllerNavigationConfigProtocol.navBackAction))
            }else {
                backBarItem = UIBarButtonItem(image: backImg, style: .plain, target: self, action: #selector(defaultNavigationBarBackAction))
            }
        }else {
            backBarItem = UIBarButtonItem(image: type(of: self).defaultNavBarBackImage, style: .plain, target: self, action: #selector(defaultNavigationBarBackAction))
        }
        viewController.navigationItem.leftBarButtonItem = backBarItem
    }
    
    /// 控制器返回键的 默认实现
    @objc private func defaultNavigationBarBackAction() {
        if let vc = topViewController?.presentingViewController {
            vc.dismiss(animated: true, completion: nil)
            return
        }
        if  viewControllers.count > 1 {
            popViewController(animated: true)
        }
    }
    
}

// MARK: - UINavigationControllerDelegate 导航栏显隐和导航栏图片样式
extension SWNavigationController: UINavigationControllerDelegate {
    public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        if let vc = viewController as? SWViewControllerNavigationConfigProtocol {
            if vc.responds(to: #selector(SWViewControllerNavigationConfigProtocol.isNavBarHidden)) {
                let hidden = vc.isNavBarHidden?() ?? false
                if hidden {
                    setNavigationBarHidden(true, animated: true)
                    return
                }
            }
            setNavigationBarHidden(false, animated: true)
            
            // 导航栏未隐藏，需要设置背景图
            var navBarImage: UIImage?
            if let navBackgroundImage = vc.navBackgroundImage, let img = navBackgroundImage() {
                navBarImage = img
            }else if let defaultNavImg = SWNavigationController.defaultNavBackgroundImage {
                navBarImage = defaultNavImg
            }
            guard let navImage = navBarImage else {
                return
            }
            navigationBar.standardAppearance.backgroundImage = navImage
            navigationBar.scrollEdgeAppearance?.backgroundImage = navImage
            return
        }
    }
    
    public override var preferredStatusBarStyle: UIStatusBarStyle {
        if let visibleViewController = self.visibleViewController {
            return visibleViewController.preferredStatusBarStyle
        }
        return .lightContent
    }
    
    public override var prefersStatusBarHidden: Bool {
        if let visibleViewController = self.visibleViewController {
            return visibleViewController.prefersStatusBarHidden
        }
        return false
    }
}

// MARK: - UIGestureRecognizerDelegate 配置页面的滑动返回
extension SWNavigationController: UIGestureRecognizerDelegate {
    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if let showVC = visibleViewController as? SWViewControllerNavigationConfigProtocol, let controllerScrollBackEnable = showVC.controllerScrollBackEnable {
            return controllerScrollBackEnable()
        }
        return true
    }
}
